package SM.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import SM.BusinessLogic.DBAccess;
import SM.BusinessLogic.DBService;
import SM.BusinessLogic.SessionVariables;


/**
 * Servlet implementation class ReportIssue
 */

public class SocietySetup extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public SocietySetup() {
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// doPost is used to Accept request from page and Make Changes
		
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("id");
		
		if(id.equals("soc"))
			this.HandleSocietyData(out, request);
		else if(id.equals("building"))
			this.HandleBuildingData(out, request);
		else if(id.equals("flat"))
			this.HandleFlatData(out, request);
		else if(id.equals("add_mem"))
			this.AddMember(out,request);
		else if(id.equals("rem_mem"))
			this.RemoveMember(out, request);
		else if(id.equals("add_resp"))
			this.AddResp(out,request);
		else if(id.equals("update"))
			this.UpdateResp(out,request);
		else if(id.equals("new_mem"))
			this.AddNewMember(out, request);
		else
			out.println("<span style='color:red;'> Some parameter problem occured </span>");
	}

	private void AddNewMember(PrintWriter out, HttpServletRequest request) {
		
		String name = request.getParameter("name");
		String bCode = request.getParameter("b_code");
		String fCode = request.getParameter("f_code");
		String contactNo = request.getParameter("contact");
		String email = request.getParameter("email");
		
		if(name == null || bCode == null || fCode == null || contactNo == null || email == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		String isRented = request.getParameter("is_rented");
		
		if(isRented == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		String tenantName = "", tenantContact = "", tenantEmail = "";
		int totalTenants = 0;
		
		int tenantId = 0;
		
		if(isRented.equals("1"))
		{
			try{
				
				totalTenants = Integer.parseInt((String)request.getParameter("no_of_tenants"));
				
			}catch(NumberFormatException nfe)
			{
				out.println("<span style='color:red;'> no. of Tenants should be a number </span>");
				return;
			}
			tenantName = request.getParameter("t_name");
			tenantContact = request.getParameter("t_contact");
			tenantEmail = request.getParameter("t_email");
			
			if(totalTenants == 0 || tenantName == null || tenantContact == null || tenantEmail == null)
			{
				out.println("<span style='color:red;'> Error while reading parameters </span>");
				return;
			}
			
			String selectQuery = "select max(tenant_id) from Tenants";
			String insertQueryTen = "insert into Tenants values(?,?,?,?,?)";
			
			Connection connection = null;
			PreparedStatement statement = null;
					
			try {
					connection = DBAccess.MakeConnection();
					statement = connection.prepareStatement(selectQuery);
					
					ResultSet idSet = DBService.ExecuteStatement(connection, statement);
				
					if(idSet.next())
					{
						tenantId = idSet.getInt(1) + 1;
					}
					else
					{
						tenantId = 1;
					}
					
					statement.close();
					
					statement = connection.prepareStatement(insertQueryTen);
					
					statement.setInt(1, tenantId);
					statement.setInt(2, totalTenants);
					statement.setString(3, name);
					statement.setString(4, contactNo);
					statement.setString(5, email);
					
					statement.executeUpdate();
					
			}catch(SQLException SQLEx)
			{
				System.out.println("Exception in new member add\nMessage : " + SQLEx.getMessage());
				return;
			}
			finally{
				DBAccess.CloseConnection(connection);
				DBAccess.CloseStatement(statement);
			}
		} //if ends
		
		String insertQueryMem = "insert into SocietyMembers values(?,?,?,?,?)";
		
		Connection connection = null;
		PreparedStatement statement = null;
				
		try {
				connection = DBAccess.MakeConnection();
				statement = connection.prepareStatement(insertQueryMem);
				
				statement.setString(1, name);
				statement.setString(2, bCode);
				statement.setString(3, fCode);
				statement.setString(4, contactNo);
				statement.setString(5, email);
				statement.setInt(6, tenantId);
				
				statement.executeUpdate();
				
				statement.close();
				
		}catch(SQLException SQLEx)
		{
			System.out.println("Exception in new member add\nMessage : " + SQLEx.getMessage());
			return;
		}
		finally{
			DBAccess.CloseConnection(connection);
			DBAccess.CloseStatement(statement);
		}
	}

	private synchronized void UpdateResp(PrintWriter out, HttpServletRequest request) {
		
		String name_list = request.getParameter("name_list");
		String resp_list = request.getParameter("resp_list");
		boolean updated = false;
		
		if(name_list == null || resp_list == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		String[] names = name_list.split(",");
		String[] resps = resp_list.split(",");
		
		String selectQuery = "select * from CommitteeInfo where email = ? and resp_id = ?";
		
		String updateQuery = "update CommitteeInfo " +
				"set resp_id = ? " +
				"where email = ?";
		
		for(int i=0;i<names.length;i++)
		{
			String name = names[i];
			String resp = resps[i];
		
			if(!DBService.IsRecordPresent(selectQuery, name, resp))
			{
				DBService.ExecuteQuery(updateQuery, resp, name);
				updated = true;
			}
		}
		String update = (updated) ? "<span style='color:green;'>Updated Successfully</span>" : "<span style='color:red;'>Nothing to update</span>";
		
		out.println(update);
	}

	private void AddResp(PrintWriter out, HttpServletRequest request) {
		String respName = request.getParameter("resp_name");
		String respCode = request.getParameter("resp_code");
		
		if(respName == null || respCode == null)
		{
			out.println("<span style='color:red'>Error while reading parameters</span>");
			return;
		}
		
		String selectQuery = "select * from Responsibilities where resp_id = ? or resp_name = ?";
		
		if(DBService.IsRecordPresent(selectQuery, respCode, respName))
		{
			out.println("<span style='color:red'>" + respCode + " or " + respName + " is already been assigned</span>");
			return;
		}
		
		String insertQuery = "insert into Responsibilities(resp_id,resp_name) values(?,?)";
		
		DBService.ExecuteQuery(insertQuery, respCode,respName);
		
		out.println("<span style='color:green'>"  + respName + " is successfully added</span>");
	}

	private void HandleSocietyData(PrintWriter out, HttpServletRequest req)
	{
		String societyName = req.getParameter("name");
		String societyDesc = req.getParameter("desc");
		
		if(societyName == null || societyDesc == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		SM.BusinessLogic.SocietySetup Setup = new SM.BusinessLogic.SocietySetup();
		
		Setup.SocietyInfoUpdate(societyName, societyDesc);
		
		SessionVariables.SetSocName(null, req);
		
		out.println("<span style='color:green;'> Society name changed </span>");
	}
	
	private void HandleBuildingData(PrintWriter out, HttpServletRequest req)
	{
		String bName = req.getParameter("name");
		String bDesc = req.getParameter("desc");
		String bCode = req.getParameter("code");
		
		if(bName == null || bDesc == null || bCode == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		SM.BusinessLogic.SocietySetup Setup = new SM.BusinessLogic.SocietySetup();
		
		if(Setup.IsBuildingPresent(bCode))
		{
			out.println("<span style='color:red;'> Building Code " + bCode + " is already been assigned.</span>");
			return;
		}
		
		Setup.BuildingCodesInsert(bName, bCode, bDesc);
		
		out.println("<span style='color:green;'> Building " + bName + " added </span>");
	}
	
	private void HandleFlatData(PrintWriter out, HttpServletRequest req)
	{
		String FlatRange = req.getParameter("flat_range");
		
		String[] Ranges = FlatRange.split(",");
		
		for(int Index = 0; Index < Ranges.length; Index ++)
		{
			String[] Range = Ranges[Index].split("-");
			
			if(Range.length > 2)
			{
				out.println("<span style='color:red;'> Provided range is Wrong </span>");
				return;
			}
			
			try {
					int start = Integer.parseInt(Range[0]);
					int end = Integer.parseInt(Range[1]);
					
					if(start > end)
					{
						out.println("<span style='color:red;'> " + start +" is greater than " + end +" </span>");
						return;
					}
					
					for(int flat_no = start; flat_no <= end; flat_no++)
					{
						SM.BusinessLogic.SocietySetup Setup = new SM.BusinessLogic.SocietySetup();
						
						if(!Setup.IsFlatNumberPresent(flat_no))
						{
							Setup.FlatNumbersInsert(flat_no);
						}
					}
					
					
			}catch(NumberFormatException nfe)
			{
				out.println("<span style='color:red;'> Range should contain numbers only </span>");
				return;
			}
		}
		
		out.println("<span style='color:green;'> Flat range added </span>");
	}
	
	/*Following functions add and remove member data*/
	
	private void AddMember(PrintWriter out, HttpServletRequest req)
	{
		String memberName = req.getParameter("name");
		String resp = req.getParameter("resp");
		String email = req.getParameter("mail");
		String contact = req.getParameter("contact_no");
		
		if(memberName == null || resp == null || email == null || contact == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		String selectQuery = "select * from Credentials where username = ?";
		
		if(!DBService.IsRecordPresent(selectQuery, email))
		{
			out.println("<span style='color:red;'> " + email + " has not signed up." + 
					" It is mandatory to have account before becoming a member.</span>");
			return;
		}
		
		SM.BusinessLogic.SocietySetup setup = new SM.BusinessLogic.SocietySetup();
		
		String outText = setup.AddMember(memberName, resp, email, contact);
		
		out.println(outText);
		
	}
	
	private void RemoveMember(PrintWriter out, HttpServletRequest req)
	{
		String memberName = req.getParameter("name");
		
		if(memberName == null)
		{
			out.println("<span style='color:red;'> Error while reading parameters </span>");
			return;
		}
		
		SM.BusinessLogic.SocietySetup setup = new SM.BusinessLogic.SocietySetup();
		
		setup.RemoveMember(memberName);
		
		out.println("<span style='color:green;'> " + memberName + " is now removed </span>");
	}
}
